pwd
ls
cd
python hello_world.py
Some programs take arguments
cd directory
python script.py
Can we write a python script that takes arguments?
arg_demo.py
¶Program arguments are usually separated by spaces.
If you want to include a space in your argument, surround your argument with single quotes.
python arg_demo.py separate arguments
vs
python arg_demo.py 'single argument'
The terminal uses many special symbols for different purposes.
For example, { } ( ) < > | & * $ @ ! ~
all have a special functions.
If you want to include a symbol in a program argument, it's a good idea to wrap it in single quotes.
python arg_demo.py * 7
vs
python arg_demo.py '*' 7
What is sys.argv
?
A list!
What if I just want the "first" argument? How would I get it...?
hello.py
¶You can access a specific item in a list (or string!) using the indexing operator [...]
.
[0]
[1]
Remember that the first item in sys.argv
(i.e. sys.argv[0]
) is the name of your script!
What happens when you have more commandline arguments than the program uses?
The extra arguments are ignored.
What happens when you don't supply as many arguments as the program uses?
You will get an IndexError
when python tries to grab a value from a list position that doesn't exist.
repeat.py
¶Write a program that prompts the user to input things. After they are done, print the list of things.
The number of things to input and the prompt text should be specified on the commandline.
$ python things.py 3 'Fruit or veggy' Fruit or veggy: apple Fruit or veggy: pear Fruit or veggy: broccoli - apple - pear - broccoli
$ python things.py 5 Major Major: Bioinformatics Major: Mathematics Major: Linguistics Major: Vocal Performance Major: History - Bioinformatics - Mathematics - Linguistics - Vocal Performance - History
things.py
¶sys.argv
[0]
, [1]
, etc.